package org.xtense.rcp.views;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;
import org.xtense.rcp.editors.DatabaseViewer;
import org.xtense.rcp.editors.XmlEditor;
import org.xtense.rcp.editors.input.DatabaseViewerInput;
import org.xtense.rcp.editors.input.XmlEditorInput;
import org.xtense.rcp.util.ITreeEntry;

public class NavigatorView extends ViewPart {
	public static String View_ID = "XtenseRCP.NavigatorView";

	@Override
	public void createPartControl(Composite parent) {
		Composite topComp = new Composite(parent, SWT.NONE);
		topComp.setLayout(new FillLayout());

		TreeViewer tv = new TreeViewer(topComp, SWT.NONE);
		NagivatorTreeViewProvider provider = new NagivatorTreeViewProvider();
		tv.setContentProvider(provider);
		tv.setLabelProvider(provider);

		tv.setInput(this.createNavigatorTree());

		tv.addSelectionChangedListener(new ISelectionChangedListener() {

			@Override
			public void selectionChanged(SelectionChangedEvent event) {
				IStructuredSelection sel = (IStructuredSelection) event
						.getSelection();
				NavigatorEntry entry = (NavigatorEntry) sel.getFirstElement();
				IEditorInput editorInput = entry.getEditorInput();
				String editorID = entry.getEditorId();
				if (editorInput == null || editorID == null)
					return;

				IWorkbenchPage workbenchPage = getViewSite().getPage();
				IEditorPart editor = workbenchPage.findEditor(editorInput);
				if (editor != null) {
					workbenchPage.bringToTop(editor);
				} else {
					try {
						editor = workbenchPage
								.openEditor(editorInput, editorID);
					} catch (PartInitException e) {
						e.printStackTrace();
					}
				}

			}

		});
		tv.setSelection(new StructuredSelection(new Object[] { tv.getTree()
				.getItem(0).getData() }));
	}

	private List<ITreeEntry> createNavigatorTree() {
		List<ITreeEntry> tree = new ArrayList<ITreeEntry>();
		NavigatorEntry b = new NavigatorEntry("XML Editor");
		b.setEditorInput(new XmlEditorInput());
		b.setEditorId(XmlEditor.class.getName());
		NavigatorEntry c = new NavigatorEntry("Database Viewer");
		c.setEditorInput(new DatabaseViewerInput());
		c.setEditorId(DatabaseViewer.class.getName());
		tree.add(b);
		tree.add(c);
		return tree;
	}

	@Override
	public void setFocus() {
		// TODO Auto-generated method stub

	}

}
